package com.nf.health.app.sweat.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.nf.health.app.AfinalDb.MeasureDataDao;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.my.MyShopStoreActivity;
import com.nf.health.app.adapter.OnMyClickListener;
import com.nf.health.app.customview.SweatPrePopupWindow;
import com.nf.health.app.http.Act;
import com.nf.health.app.sweat.bean.SweatBean;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by hepan on 2016/5/21.
 * <p>
 * 汗液数据采集的前期处理
 */
public class PreSweatAnalyzerActivity extends BaseActivity {
    private static final String TAG = PreSweatAnalyzerActivity.class.getSimpleName();
    private static final long INTERVAL_TIME = 3 * 1000;
    private static final String FLAG_ADD_DATA_CACHE = "flag_add_data_cache";
    @Bind(R.id.titlebar_right_view)
    ImageView titlebarRightView;
    @Bind(R.id.btn_start_sweat_measure)
    Button btnStartSweatMeasure;
    @Bind(R.id.iv_no_device)
    ImageView ivNoDevice;
    @Bind(R.id.tv_hint)
    TextView tvHint;
    @Bind(R.id.btn_history)
    Button btnHistory;
    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    private BluetoothAdapter mBluetoothAdapter;
    private List<BluetoothDevice> devices = new ArrayList<>();
    private String deviceAddressUp = "";
    private String deviceAddressDown = "";
    private MaterialDialog materialDialog;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                default:
                    break;
            }
        }
    };
    //缓存数据集合
    private List<SweatBean> cacheInfos;
    private int upload_cache_index = 0;//记录当前上传数据位置
    private boolean isScanDown = false;//记录是否扫描下面的设备

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_pre_sweatanalizy);
        ButterKnife.bind(this);
        //获取存储的汗液地址
        deviceAddressUp = PreferenceHelper.getString(PreferenceHelper.SWEAT_NANLYZER_ADDRESS_ONE, "");
        deviceAddressDown = PreferenceHelper.getString(PreferenceHelper.SWEAT_NANLYZER_ADDRESS_TWO, "");
        ViewUtil.setText(this, R.id.titlebar_title_tv, "汗液数据");
        titlebarRightView.setImageResource(R.drawable.ic_title_setting);
        initBluetooth();
        initListener();
        //根据蓝牙地址处理ui
        initViewByAddress();
        //检测是否有缓存数据
        checkCacheData();
    }

    /********
     * 初始化蓝牙
     *******/
    private void initBluetooth() {
        // 检查当前手机是否支持blue 蓝牙,如果不支持退出程序
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //扫描ble蓝牙的回调
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (device != null) {
                                if (!TextUtils.isEmpty(device.getName())) {
                                    if (device.getName().contains("NFSMA")) {//"NFSMA"
                                        if (!devices.contains(device)) {
                                            devices.add(device);
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            };
        } else {
            showToast("设备蓝牙版本过低");
            finish();
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }


    private void initListener() {
        titlebarRightView.setOnClickListener(this);
        btnStartSweatMeasure.setOnClickListener(this);
        btnHistory.setOnClickListener(this);
    }

    //根据蓝牙地址做一些判断
    private void initViewByAddress() {
        if (TextUtils.isEmpty(deviceAddressUp + deviceAddressDown)) {
            tvHint.setText("您还未绑定设备,请先绑定");
            btnStartSweatMeasure.setText("绑定设备");
        } else {
            tvHint.setText("您的设备还没有链接,请点击同步连接设备");
            btnStartSweatMeasure.setText("同步数据");
        }
    }

    /**
     * 创建的时候,看是否有缓存数据,用来上传
     */
    private void checkCacheData() {
        cacheInfos = MeasureDataDao.getAllSweat();
        if (cacheInfos != null && cacheInfos.size() > 0) {
            uploadCacheData(0);
        }
    }

    /**
     * 上传缓存数据
     *
     * @param index 上传缓存数据在集合中位置
     */
    private void uploadCacheData(int index) {
        if (index >= cacheInfos.size()) {
            hideLoading(true);
            return;
        }
        upload_cache_index = index;
        try {
            showLoading("上传缓存...");
            String datas = cacheInfos.get(index).getData();
            provider.AddSweatDataNew("2", datas);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.titlebar_right_view://右上角弹出popupwindow
                showPop();
                break;
            case R.id.btn_history://历史数据
                ActivityUtils.showActivity(this, SweatAnalyzerHistoryTrackActivity.class);
                break;
            case R.id.btn_start_sweat_measure://绑定设备,和同步数据是同一个按钮,根据是否绑定设备来处理逻辑
                if (TextUtils.isEmpty(deviceAddressUp+deviceAddressDown)) {
                    isScanDown = false;
                    scanLeDevice(true);
                } else {
                    ActivityUtils.skipActivity(this, SweatAnalyzerNewActivity.class);
//                    SweatBluetoothUtils.test();
                }

                break;
        }
    }

    private void showPop() {
        SweatPrePopupWindow pop = new SweatPrePopupWindow(this, deviceAddressUp, deviceAddressDown);
        pop.showAsDropDown(titlebarRightView);
        pop.setOnMenuItemClickListener(new OnMyClickListener() {
            @Override
            public void onClick(int position, String flag) {
                if (R.id.ll_bind_device_up == position) {
                    if (!TextUtils.isEmpty(deviceAddressUp)) {
                        //TODO 解绑操作
                        PreferenceHelper.putString(PreferenceHelper.SWEAT_NANLYZER_ADDRESS_ONE, "");
                        showToast("解绑成功");
                        deviceAddressUp = "";//要赋值,点击跳转要根据其判断
                        initViewByAddress();
                    } else {
                        isScanDown = false;
                        scanLeDevice(true);
                    }
                } else if (R.id.ll_bind_device_down == position) {
                    if (!TextUtils.isEmpty(deviceAddressDown)) {
                        //TODO 解绑操作
                        PreferenceHelper.putString(PreferenceHelper.SWEAT_NANLYZER_ADDRESS_TWO, "");
                        showToast("解绑成功");
                        deviceAddressDown = "";//要赋值,点击跳转要根据其判断
                        initViewByAddress();
                    } else {
                        isScanDown = true;
                        scanLeDevice(true);
                    }
                } else if (R.id.tv_have_no_device == position) {
                    ActivityUtils.showActivity(PreSweatAnalyzerActivity.this, MyShopStoreActivity.class);
                }
            }
        });
    }

    /**
     * 扫描设备
     ********/
    private void scanLeDevice(final boolean enable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (enable) {
                showLoading("查找设备中..");
                devices.clear();
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                // Stops scanning after a pre-defined scan period.
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            mBluetoothAdapter.stopLeScan(mLeScanCallback);
                            hideLoading();
                            try {
                                showBluetoothNames();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }, INTERVAL_TIME);
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
                try {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                } catch (Exception e) {
                }
            }
        }
    }

    private void showBluetoothNames() {
        if (devices.size() <= 0) {
            if (!isFinishing()) {
                Util.showNotHasFountDeviced(PreSweatAnalyzerActivity.this);
            }
            return;
        }
        final String[] deviceNames = new String[devices.size()];
        for (int i = 0; i < devices.size(); i++) {
            String address = devices.get(i).getAddress();
            deviceNames[i] = "汗液仪-" + address.replace(":", "");
        }
        if (!isFinishing()) {
            if (materialDialog == null) {
                materialDialog = new MaterialDialog.Builder(PreSweatAnalyzerActivity.this)
                        .title("汗液仪")
                        .items(deviceNames)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                String address = devices.get(which).getAddress();
                                if (isScanDown) {
                                    if (address.equals(deviceAddressUp)) {
                                        showToast(deviceAddressUp + " 已被绑定");
                                        return;
                                    }
                                    PreferenceHelper.putString(PreferenceHelper.SWEAT_NANLYZER_ADDRESS_TWO, address);
                                    deviceAddressDown = address;
                                    initViewByAddress();
                                    dialog.dismiss();
                                } else {
                                    if (address.equals(deviceAddressDown)) {
                                        showToast(deviceAddressDown + " 已被绑定");
                                        return;
                                    }
                                    PreferenceHelper.putString(PreferenceHelper.SWEAT_NANLYZER_ADDRESS_ONE, address);
                                    deviceAddressUp = address;
                                    initViewByAddress();
                                    dialog.dismiss();
                                }

//                                ActivityUtils.skipActivity(PreSweatAnalyzerActivity.this, SweatAnalyzerActivity.class);
                            }
                        }).show();
            } else {
                if (!isFinishing()) {
                    materialDialog.show();
                }
            }
        }
    }

//    /**
//     * 显示搜索到已绑定设备
//     */
//    private void showBindDevice() {
//        int color = 0xbb2E86F4;
//        new MaterialDialog.Builder(this)
//                .titleColor(color)
//                .positiveColor(color)
//                .negativeColor(color)
//                .title("发现已绑定设备:")
//                .content(deviceAddress + "\n是否同步此设备数据?")
//                .positiveText("同步")
//                .negativeText("否")
//                .onPositive(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        ActivityUtils.skipActivity(PreSweatAnalyzerActivity.this, SweatAnalyzerActivity.class);
//                    }
//                }).onNegative(new MaterialDialog.SingleButtonCallback() {
//            @Override
//            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                dialog.dismiss();
//            }
//        }).show();
//    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (Act.Flag.FLAG_ADD_SWEAT.equals(actionName)) {
//            GetToast.useString(this,"缓存数据上传成功 位置" + upload_cache_index);
            provider.requestAddScore("18", "");//添加积分
            MeasureDataDao.deleteSweatById(cacheInfos.get(upload_cache_index).getId());
            uploadCacheData(++upload_cache_index);
            System.out.println("success");
        }
    }

    @Override
    public void handleActionFinish(String actionName, Object object) {
//        super.handleActionFinish(actionName, object);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (!TextUtils.isEmpty(deviceAddress)) {
//            //绑定过设备,查找此设备是否在周围
//            scanLeDevice(true);
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }
}
